<script setup lang="ts">
import DocumentationIcon from './icons/IconDocumentation.vue'
import ToolingIcon from './icons/IconTooling.vue'
import EcosystemIcon from './icons/IconEcosystem.vue'
import CommunityIcon from './icons/IconCommunity.vue'
import SupportIcon from './icons/IconSupport.vue'
</script>

<template>
  <div class="container">
    <div class="content">
      <h1 class="title">今天有人过生日吗？祝福一下吧！</h1>
      <div class="cake" :class="{ 'animate-cake': cakeAnimate }">🎂</div>
      <el-button 
        type="primary" 
        size="large" 
        @click="submit()" 
        :loading="loading"
      >祝福他</el-button>
      <div v-if="errorMsg" class="error-message">{{ errorMsg }}</div>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, reactive, getCurrentInstance, nextTick, onBeforeMount, onMounted } from 'vue'
import request from '../utils/request'
import api from '../utils/Api'

var ipAddressParam = ref('')
const errorMsg = ref(null);

// 添加一个状态来跟踪是否正在获取IP
const isGettingIp = ref(false)

const loading = ref(false)
const cakeAnimate = ref(false)

onBeforeMount(() => {
  // 组件加载时就开始获取IP
  getLocalIp()
});

const getLocalIp = async () => {
  isGettingIp.value = true
  const RTCPeerConnection = window.RTCPeerConnection;
  if (RTCPeerConnection) {
    const pc = new RTCPeerConnection({ iceServers: [] });
    pc.createDataChannel('');
    pc.createOffer().then(sdp => pc.setLocalDescription(sdp)).catch(console.error);
    
    return new Promise((resolve) => {
      pc.onicecandidate = ice => {
        if (ice && ice.candidate && ice.candidate.candidate) {
          const s = ice.candidate.candidate.split(' ');
          if (s[7] === 'host') {
            pc.onicecandidate = null;
            ipAddressParam.value = s[4];
            isGettingIp.value = false
            resolve(s[4])
          }
        }
      };
    });
  } else {
    isGettingIp.value = false
    console.error('暂不支持获取本地IP,请输入本地IP');
    return Promise.reject('不支持获取本地IP');
  }
};

const submit = async () => {
  loading.value = true
  try {
    // 如果还没有IP地址且不在获取过程中，先获取IP
    if (!ipAddressParam.value && !isGettingIp.value) {
      await getLocalIp();
    }
    
    // 确保有IP地址后再发送请求
    if (ipAddressParam.value) {
      let result = await request({
        url: '/celebrate/count',
        params: {
          ipAddress: ipAddressParam.value.split('.')[0]
        },
        showError: false,
        errorCallback: (response) => {
          errorMsg.value = response.info
        }
      });
      console.log(result);

      // 如果请求成功，触发蛋糕动画
      cakeAnimate.value = true
      setTimeout(() => {
        cakeAnimate.value = false
      }, 1000)
    } else {
      errorMsg.value = '无法获取IP地址';
    }
  } catch (error) {
    console.error('提交失败:', error);
    errorMsg.value = '提交失败';
  } finally {
    loading.value = false
  }
}

</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.title {
  color: #303133;
  font-size: 24px;
  margin: 0;
  text-align: center;
}

.cake {
  font-size: 40px;
  transition: transform 0.3s ease-in-out;
}

.animate-cake {
  transform: scale(1.5);
}

.error-message {
  margin-top: 10px;
  color: #f56c6c;
}
</style>